import React, { Component } from 'react';
import jsapi from './utils/jsapi';
import axios from 'axios';
import queryString from 'query-string';
import declare from 'ft-declare';
import './App.css';


export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      selectedRecords: [],
      map: null
    }

    this.change = this.change.bind(this);
  }

  async change(value) {
    const [Basemap, BasemapLayer] =
      await jsapi.load(['esri/map', 'esri/dijit/Basemap']);
    console.log("map", this.state.map);
    if (value === 0) {
      const basemap = new Basemap({
        id: 'air',
        layers: [new BasemapLayer({ url: `http://localhost:7080/PBS/rest/services/air_image/MapServer` })]
      });
      this.state.map.setBasemap(basemap);
    } else {
      this.state.map.setBasemap(new Basemap({
        id: 'zw',
        layers: [new BasemapLayer({ url: `http://localhost:7080/PBS/rest/services/air_image/MapServer` })]
      }));
    }
  }

  async componentDidMount() {
    const that = this;
    const [Map, Basemap, BasemapLayer, Extent, DynamicMapServiceLayer] =
      await jsapi.load(['esri/map', 'esri/dijit/Basemap', 'esri/dijit/BasemapLayer', 'esri/geometry/Extent', 'esri/layers/DynamicMapServiceLayer']);

    const MyDynamicMapServiceLayer = declare(DynamicMapServiceLayer, {
      constructor: function (url, options) {
        this.initialExtent = this.fullExtent = new Extent({ "xmin": options.xmin, "ymin": options.ymin, "xmax": options.xmax, "ymax": options.ymax });
        this.loaded = true;
        this.wmsUrl = url;
        this.onLoad(this);
      },

      getImageUrl: function (extent, width, height, callback) {
        var params = {
          service: 'wms',
          request: "GetMap",
          transparent: true,
          format: "image/png",
          version: "1.1.0",
          layers: "hq:data_kxgh",
          exceptions: "application/vnd.ogc.se_xml",

          //changing values
          bbox: extent.xmin + "," + extent.ymin + "," + extent.xmax + "," + extent.ymax,
          srs: "EPSG:999419",
          width: width,
          height: height
        };

        // callback("http://localhost:8080/geoserver/hq/wms");
        callback(this.wmsUrl + queryString.stringify(params));
      }
    });
    const map = new Map("map", {
      zoom: 3,
      basemap: new Basemap({
        id: 'air',
        layers: [new BasemapLayer({ url: `http://localhost:7080/PBS/rest/services/air_image/MapServer` }), new BasemapLayer({ url: `http://localhost:7080/PBS/rest/services/air_image/MapServer` })]
      }),
      logo: false,
      extent: new Extent({
        xmin: -40018,
        ymin: -9706,
        xmax: -7820,
        ymax: 6493,
        spatialReference: { wkt: 'PROJCS["shanghaicity",GEOGCS["GCS_Beijing_1954",DATUM["D_Beijing_1954",SPHEROID["Krasovsky_1940",6378245.0,298.3]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",-3457147.81],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",121.2751921],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]' }
      })
    });
    this.setState({ map });
    // const toggle = new BasemapToggle({
    //   map: map,
    //   basemap: new Basemap({
    //     id: 'zw',
    //     layers: [new BasemapLayer({ url: `http://localhost:7080/PBS/rest/services/air_image/MapServer` })]
    //   }),
    // }, "BasemapToggle");
    // toggle.startup();

    let kxghLayer = new MyDynamicMapServiceLayer("http://localhost:8080/geoserver/hq/wms?", {
      xmin: -23228,
      ymin: -17157,
      xmax: 5400,
      ymax: 12013
    });

    map.on("click", function (evt) {
      axios.get("http://localhost:8000/api/kxgh/list_by_point_intersect?x=" + evt.mapPoint.x + "&y=" + evt.mapPoint.y).then(function ({ data, status }) {
        console.log('response =>', data);
        that.setState({ selectedRecords: data.data })
      });
    })
    map.addLayer(kxghLayer);
  }


  render() {
    return (
      <div className="main-container">
        <div className="header">
          <span className="header-title">虹桥商务区规划土地管理平台</span>
        </div>
        <div id="map">

        </div>
        <div className="basemap-switch-container">
          <button onClick={() => this.change(0)}>影像</button>
          <button onClick={() => this.change(1)}>政务</button>
        </div>
        <div className="info-panel">
          {this.state.selectedRecords.length === 0 ?
            <div>暂无数据</div> :
            <div>
              <table>
                <tbody>
                  <tr>
                    <td width="85">项目编号</td>
                    <td width="155">{this.state.selectedRecords[0]['xmbh']}</td>
                  </tr>
                  <tr>
                    <td>地块编号</td>
                    <td>{this.state.selectedRecords[0]['dkbh']}</td>
                  </tr>
                  <tr>
                    <td>用地代码</td>
                    <td>{this.state.selectedRecords[0]['yddm']}</td>
                  </tr>
                  <tr>
                    <td>用地性质</td>
                    <td>{this.state.selectedRecords[0]['xz']}</td>
                  </tr>
                  <tr>
                    <td>单元编号</td>
                    <td>{this.state.selectedRecords[0]['dybh']}</td>
                  </tr>
                  <tr>
                    <td>区县</td>
                    <td>{this.state.selectedRecords[0]['qxMc']}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          }
        </div>
      </div>

    )
  }
}